import { BaseContext } from 'koa'
import { getManager, Repository } from 'typeorm'
import { Project } from '../entity/project'
import { OKBody, FailBody } from '../utils/requests/index'
import { shouldBlock } from '../utils/middleware/parseCtxSession'

export default class HTMLController {
  public static async uploadFilePage(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.redirect('/')
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    await ctx.render('upload/index', {
      title: 'Sketch Measure设计稿上传',
    })
  }

  public static async index(ctx: BaseContext) {
    await ctx.render('index/index.html', {
      title: 'Elegant Designer',
      desc: '优雅地交接设计工作',
    })
  }

  public static async projectIndex(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.redirect('/')
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    await ctx.render('project/index.html', {
      title: 'Elegant Designer',
      desc: '优雅地交接设计工作',
    })
  }

  public static async sketchDesignHTML(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.redirect('/')
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    const prjId: number = +ctx.params.id
    if (prjId === undefined) throw new Error('项目不存在')

    try {
      const repo: Repository<Project> = getManager().getRepository(Project)
      const data: Project = await repo.findOne({
        id: prjId
      })
      // console.log(data)
      const a = JSON.parse(data.staticFiles)

      await ctx.render('project/detail.html', {
        title: data.title || 'Elegant Designer',
        appJSONFile: a.configJSON,
      })
    } catch (err) {
      console.log(err)
    }
  }
}
